<?php


namespace app\admin\controller;


use app\common\controller\Adminbase;
use think\Db;

class Content extends Adminbase
{
    protected function initialize()
    {
        parent::initialize();
    }

    //设置
    public function index()
    {
        if ($this->request->isAjax()) {
            $_list = Db::name('content')
                ->where(['is_del' => 0])
                ->order('sort desc')
                ->select();
            $_list2=listToTree($_list);
            $_list3=array();
            foreach ($_list2 as $k=>$v){
                unset($_list2[$k]['_child']);
                $_list3[]=$_list2[$k];
                if ($v['_child']){
                    foreach ($v['_child'] as $k2=>$v2){
                        $v2['name']='├─'.$v2['name'];
                        $_list3[]=$v2;
                    }
                }
            }
            $result = ["code" => 0, "count" => '', "data" => $_list3];
            return json($result);
        }
        return $this->fetch();
    }

    //增加
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data['row']['pid']){
                $data['row']['pid']=0;
            }
            $stmt = Db::name('content')->insertGetId($data['row']);
            if ($stmt) {
                $this->success('操作成功！');
            } else {
                $this->error('操作失败！');
            }
        }
        $pid = $this->request->param('pid/d', null);
        $this->assign([
            'pid'=>$pid
        ]);
        return $this->fetch();
    }

    public function edit()
    {
        $id = $this->request->param('id/d', 0);
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data = Db::name('content')
                ->where('id', $data['row']['id'])
                ->update($data['row']);
            $this->success('操作成功');
        }
        $data = Db::name('content')->find($id);
        $this->assign([
            'data' => $data,
        ]);
        return $this->fetch();
    }

    //删除
    public function del()
    {
        $ids = $this->request->param('ids/a', null);
        try {
            foreach ($ids as $id) {
                $c_ids=Db::name('content')->where('pid','=',$id)->column('id');
                $c_ids[]=$id;
                Db::name('content')->where('id','in',$c_ids)->update([
                    'is_del' => 1,
                ]);
            }
        } catch (\Exception $ex) {
            $this->error($ex->getMessage());
        }
        $this->success('删除成功！');
    }

    public function setstate()
    {
        $id = $this->request->param('id/d', 0);

        $status = $this->request->param('value/d');

        if (Db::name('content')->where('id', $id)->update(['status' => $status])) {

            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

}